<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="addPermission(1, '0')"
          >添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button
                v-if="scope.row.type === 1"
                type="text"
                @click="addPermission(2, scope.row.id)"
              >添加</el-button>
              <!-- 父级传过来的id,scope.row.id,2为添加按钮权限 -->
              <!-- 子添加权限的时候需要获取到父亲的id -->
              <el-button
                type="text"
                @click="editPermission(scope.row.id)"
              >编辑</el-button>
              <el-button type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit ? '编辑权限点' : '新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form
            ref="perForm"
            :model="formData"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width: 90%" />
            </el-form-item>
            <el-form-item label="权限描述" required>
              <el-input v-model="formData.description" style="width: 90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button
                size="small"
                type="primary"
                @click="submitPermission"
              >确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail,
  updatePermission, delPermission
} from '@/api/permission'
// 转换成树状结构数据
import { tranListToTreeData } from '@/utils/index'
export default {
  name: 'Permission',
  data() {
    // 验证权限名称
    const validName = (rule, value, callback) => {
      let exitvalidName = this.originList.filter(item => item.pid === this.formData.pid)

      // 验证编辑
      // 1.点击编辑,先获取兄弟节点
      // 2.将自身排除,将返回的兄弟节点赋值给originList
      if (this.isEdit) {
        exitvalidName = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      exitvalidName.map(item => item.name)
        .includes(value) ? callback(new Error(`权限名称 ${value} 已经存在`)) : callback()
    }

    // 验证权限标识
    // 1.先获取所有模块数据
    // 2.将数组中code组成一个数组
    // 3.使用indules验证
    const validCode = (rule, value, callback) => {
      let exitvalidCode = this.originList
      // 点击编辑时,将自己排除在外
      if (this.isEdit) {
        exitvalidCode = this.originList.filter(item => item.id !== this.formData.id)
      }
      exitvalidCode.map(item => item.code)
        .includes(value) ? callback(new Error(`权限标识${value}已经存在`)) : callback()
    }

    return {
      originList: [], // 获取精简数据,
      isEdit: false, // 编辑状态
      permissionList: [], // 接收权限列表数据
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        // 权限名称
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        // 权限标识
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: validCode }
        ]
      }
    }
  },
  created() {
    // 调用获取权限的方法
    this.getPermissionListFn()
  },
  methods: {
    // 删除添加的权限
    delPermission(id) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delPermission(id)
        // console.log(res)
        this.getPermissionListFn()// 刷新列表
        this.$message.success(res.message)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 点击编辑获取自动回填数据
    async  editPermission(id) {
      const res = await getPermissionDetail(id)
      console.log(res)
      this.formData = res.data// 1.数据回填
      this.isEdit = true// 2.编辑状态
      this.showDialog = true// 3.弹框展开
    },
    // 确定按钮(给角色添加权限)
    submitPermission() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        // !!先验证,再判断是编辑还是添加
        if (!this.isEdit) {
          const res = await addPermission(this.formData)
          // console.log(res)
          this.$message.success(res.message)// 成功提示
        } else { // 编辑
          const res = await updatePermission(this.formData)
          console.log(res)
          this.$message.success(res.message)// 成功提示
        }
        this.showDialog = false// 弹框关闭
        this.getPermissionListFn()// 刷新列表
      })
    },
    // 添加权限
    addPermission(type, pid) {
      this.formData.type = type
      this.formData.pid = pid
      this.showDialog = true// 弹框展示
      this.isEdit = false// 非编辑状态
    },
    // 弹框取消功能
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()// 取消的时候清空校验
      this.showDialog = false
    },
    // 获取权限
    async   getPermissionListFn() {
      const res = await getPermissionList()
      // console.log(res)
      // 获取精简数据
      this.originList = res.data.map(item => ({
        name: item.name,
        id: item.id,
        code: item.code,
        pid: item.pid

      }))
      this.permissionList = tranListToTreeData(res.data)
    }
  }

}

</script>

   <style lang="scss" scoped></style>

